package WrittenTest;

import java.util.Scanner;

class MyLinkList {
    static class Node {
        public Node next = null;
        public int val;

        public Node(int val) {
            this.val = val;
        }
    }

    public Node head;

    public void endAdd(int x) {
        Node node = new Node(x);
        Node cur = this.head;
        if (this.head == null) {
            head = node;
        } else {
            while (cur.next != null) {
                cur = cur.next;
            }
        }
        if (cur != null) {
            cur.next = node;
        }
    }
}

public class test10 {
    // 礼物归谁问题
    // 算法原理：模拟，动态规划，循环链表
    public static void main(String[] args) {
        // 动态规划做法
        // 动态转移方程：dp[n] = (dp[n-1] + m) % i
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int dp = 0;
        for (int i = 1; i <= n; i++) {
            dp = (dp + m) % i;
        }
        System.out.println(dp);
    }

    public static void main1(String[] args) {
        // 循环链表做法
        MyLinkList myLinkList = new MyLinkList();
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        // 对链表进行插入元素
        for (int i = 0; i < n; i++) {
            myLinkList.endAdd(i);
        }
        // 构建出循环链表
        MyLinkList.Node cur = myLinkList.head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = myLinkList.head;
        // 变量count来记录需要删除的节点，将头结点赋给cur
        int count = 0;
        cur = myLinkList.head;
        while (n != 1) {
            // 创建pre节点来记录删除节点的前驱节点
            MyLinkList.Node pre = cur;
            count++;
            if (count == m - 1) {
                // 将待删除节点的后继赋给待删除结点的前驱
                pre.next = cur.next.next;
                n--;
                count = 0;
            }
            // cur指针来循环遍历
            cur = cur.next;
        }
        System.out.println(cur.val);
    }
}
